package reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射创建对象
 */
public class Test05 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //获得CLass对象
        Class c1 = Class.forName("reflect.User");
        //构造对象，通过无参构造
        User user = (User) c1.getDeclaredConstructor().newInstance();
        //System.out.println(user);
        //有参构造
        User user1 = (User) c1.getDeclaredConstructor(int.class, String.class).newInstance(1, "对象");
        //System.out.println(user1);

        //通过反射调用方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke(对象,"参数")
        setName.invoke(user,"对象");
        //System.out.println(user);

        //通过反射操作属性
        Field name = c1.getDeclaredField("name");
        //操作私有属性需要取消安全检测，提高效率，防止反复检查
        name.setAccessible(true);
        name.set(user, "对象2");

    }
}
